In [222]:
import pprint
import json
import urllib
import pandas as pd
import random
import numpy as np
In [223]:
def cnv2utf8(mstr):
#print mstr
#print urllib.quote(mstr.encode(u"utf8"))
return urllib.quote(mstr.encode(u"utf8"))
In [224]:
class MyPrettyPrinter(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, unicode):
return (object.encode('utf8'), True, False)
return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)
def printJson(aObj):
MyPrettyPrinter().pprint(aObj)
In [225]:
def getData(location, product, top, skip, EndDate, StartDate):
##變數宣告
# url是API的網址
# ahash是替代的變數值
url = u"http://m.coa.gov.tw/OpenData/FarmTransData.aspx?$top={top}&$skip={skip}&Market={Market}&Crop={Crop}&EndDate={EndDate}&StartDate={StartDate}"
ahash={
u"{top}" :top,
u"{skip}" :skip,
u"{Market}" :cnv2utf8(location),
u"{Crop}" :cnv2utf8(product),
u"{EndDate}" :EndDate,
u"{StartDate}":StartDate,
}
## 這裡再做的就是將ahash內的key用value換掉
for abc in ahash:
url=url.replace(abc,ahash[abc])
#print url
# 到API抓資料回來
rsps = urllib.urlopen( url.encode(u"utf8") )
np.random.seed(1337)
alist = [1, 2, 3, 4, 5]
for x in alist:
if int(np.random.random()*10)>7 :
print "X"
else:
print x
return json.loads(rsps.read())
In [226]:
pd.read_json(json.dumps(getData(u"", u"本島萵苣", u"10000", u"",u"105.06.30",u"103.05.01"))).to_csv(u"123.csv",encoding='utf-8')
url = u"http://m.coa.gov.tw/OpenData/FarmTransData.aspx?$top={top}&$skip={skip}&Market={Market}&Crop={Crop}"
ahash={
u"{top}" :u"100",
u"{skip}" :u"0",
u"{Market}":cnv2utf8(u"台北二"),
u"{Crop}" :cnv2utf8(u"椰子"),
}
## 這裡再做的就是將ahash內的key用value換掉
for abc in ahash:
url=url.replace(abc,ahash[abc])
#print url
# 到API抓資料回來
rsps = urllib.urlopen( url.encode(u"utf8") )
data = json.loads(rsps.read())
printJson(data)
In [227]:
#url = u"http://m.coa.gov.tw/OpenData/FarmTransData.aspx?$top={top}&$skip={skip}&filter={filter}"
In [228]:
#ahash={u"99110001":u"August",
# u"99110002":u"vicky"}
In [229]:
# ahash[u"99110001"]
In [230]:
# ahash={
u"{top}":u"20",
u"{skip}":u"100",
u"{filter}":u"Market=台北二&Crop=椰子",
# }
In [ ]:
# ahash
In [ ]:
#ahash
In [ ]:
# for abc in ahash:
print abc,ahash[abc]
In [ ]:
#url.replace(u"gov",u"com")
In [ ]:
#urllib.quote(u"椰子".encode(u"utf8"))
In [ ]:
#ahash={
u"{top}":u"20",
u"{skip}":u"100",
u"{filter}":urllib.quote(u"Market=台北二&Crop=椰子".encode(u"utf8")),
#}
In [ ]: